package com.nebula.util;

import com.nebula.common.Const;
import com.nebula.common.Result;
import com.nebula.entity.User;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.EnumMap;


/**
 * @author CcccX
 * @create 2019-01-14 8:37
 */
public class BaseUtil {

    public enum CheckLoginProperty {
        IS_LOGIN, USER
    }

    public static EnumMap<CheckLoginProperty, Object> checkLogin(HttpServletRequest request,
                                                                 HttpServletResponse response) throws IOException {
        EnumMap<CheckLoginProperty, Object> refMap = new EnumMap<>(CheckLoginProperty.class);

        boolean flag = true;
        HttpSession session = request.getSession();
        PrintWriter writer = response.getWriter();
        User user = (User) session.getAttribute(Const.USER_INFO);
        if (user == null){
            flag = false;
            refMap.put(CheckLoginProperty.USER, new User());
            Result<String> byErrorMessage = Result.createByErrorMessage(Const.NEED_LOGIN);
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(byErrorMessage));
        }else {
            refMap.put(CheckLoginProperty.USER,user);
        }
        refMap.put(CheckLoginProperty.IS_LOGIN, flag);

        return refMap;
    }

    /*public static Boolean checkLogin(HttpServletRequest request, HttpServletResponse response) {
        boolean flag = true;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Const.USER_INFO);
        if (user == null) {
            flag = false;
            ObjectMapper objectMapper = new ObjectMapper();
            Result<Object> byErrorMessage = Result.createByErrorMessage(Const.NEED_LOGIN);
            String errMsg = null;
            try {
                response.setContentType("text/html;charset=UTF-8");
                errMsg = objectMapper.writeValueAsString(byErrorMessage);
                response.getWriter().write(errMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }*/
}
